<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\index;

use app\common\event\Base;
use app\event\file\Attachment;
use app\model\index\Poster as PosterModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserCode as UserCodeModel;
use app\model\index\Order as OrderModel;
use app\model\index\CreditcardOrder as CreditcardOrderModel;

use app\model\ucenter\UserTask as UserTaskModel;
use app\event\ucenter\User as UserEvent;
use app\model\app\Dynamic as DynamicModel;
use app\model\app\UserDynamic as UserDynamicModel;
use think\Exception;
use think\exception\HttpException;
use think\facade\Db;
use think\facade\Log;
use think\Image as ImageThink;

class Share extends Base
{


    /**
     * 初始化海报
     */
//    public function poster($user)
//    {
//        try {
//            $shareUrl = 'http://wechat.mayichuangye168.com/#/signin?inviteCode=' . $user['shareCode'];
//            $QR = '/upload/share_app/code/' . $user['shareCode'] . '.png';
//            if (!is_file(public_path() . $QR)) {
//                $data['code_image'] = create_qr_code($shareUrl, $QR, './upload/logo.png');
//            } else {
//                $data['code_image'] = $QR;
//            }
//            $data['share_title'] = '邀请加入云副业';
//            $data['share_desc'] = '邀请加入云副业';
//            $data['register_url'] = 'http://wechat.mayichuangye168.com/#/signin?inviteCode=' . $user['shareCode'];
//
//            $data['code_image'] = $this->request->domain() . $data['code_image'];
//            $posterIds = PosterModel::where('status', 1)->column('id');
//            $userPosterIds = UserCodeModel::where('user_id', $user['id'])->where('poster_id', 'in', $posterIds)->column('poster_id');
//            if (count($userPosterIds) < count($posterIds)) {
//                // 重建海报
//                $posters = PosterModel::where('status', 1)->where('id', 'in', array_diff($posterIds, $userPosterIds))->select();
//                $insert = [];
//                foreach ($posters as $poster) {
//                    if (is_file(public_path() . $poster['poster_image'])) {
//                        $poster_file = 'c_posters-' . $user['id'] . '-' . $poster['id'] . '.png';
//                        $insert = [
//                            'poster_id' => $poster['id'],
//                            'shareCode' => $user['shareCode'],
//                            'shareNum' => 0,
//                            'handleNum' => 0,
//                            'encryptionCode' => md5($user['shareCode'] . $user['id']),
//                            'uid' => $user['id'],
//                            'user_id' => $user['id'],
//                            'code_image' => $data['code_image'],
//                            'poster_image' => '/' . createPoster($user['id'], $poster['poster_image'], $QR, 'upload/share_app/poster/' . $poster_file)
//                        ];
//                        UserCodeModel::create($insert);
//                    }
//                }
//            }
//            $data['posters'] = UserCodeModel::where('user_id', $user['id'])->where('poster_id', 'in', $posterIds)->select();
//            $rep['code'] = 0;
//            $rep['data'] = $data;
//            $rep['message'] = 'ok';
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $rep['code'] = 2;
//            $rep['message'] = $e->getMessage();
//            $rep['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $rep;
//    }


    public function info($param, $user)
    {
        try {
            if (!$user) {
                throw new Exception('请重新登录！');
            }
            $dynamic = DynamicModel::where('id', $param['id'])->find();
            if (!$dynamic) {
                throw new Exception('当前动态不可用');
            }
            $path = str_replace('\\', DIRECTORY_SEPARATOR, $dynamic['image']['path']);
            if (!is_file(public_path() . $path)) {
                throw new Exception('当前动态暂不支持分享' . public_path() . $path);
            }
            $this->_getQrcode($user, $QR, $shareUrl);
            $common['code_image'] = $QR;
            $common['register_url'] = $shareUrl;
            $userDynamic = UserDynamicModel::where('user_id', $user['id'])->where('poster_id', $dynamic['id'])->where('image_id', $dynamic['image_id'])->find();
            if (!$userDynamic) {
                // 新增
                $poster_file = 'c_posters-' . $user['id'] . '-' . $dynamic['image_id'] . '-' . $dynamic['id'] . '.png';
                $insert = [
                    'share_title' => $dynamic['title'],
                    'share_desc' => $dynamic['summary'],
                    'poster_id' => $dynamic['id'],
                    'image_id' => $dynamic['image_id'],
                    'shareCode' => $user['shareCode'],
                    'shareNum' => 0,
                    'handleNum' => 0,
                    'encryptionCode' => md5($user['shareCode'] . $user['id']),
                    'uid' => $user['id'],
                    'user_id' => $user['id'],
                    'code_image' => $common['code_image'],
                    'poster_image' => '/' . createPoster($user['id'], $path, $QR, 'upload/share_app/poster/' . $poster_file)
                ];
                $userDynamic = UserDynamicModel::create($insert);
            }
            $rep['code'] = 0;
            $common['code_image'] = $this->request->domain() . $common['code_image'];
            $rep['data']['common'] = $common;
            $rep['data']['user_dynamic'] = $userDynamic;
            $rep['message'] = 'ok';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep['code'] = 2;
            $rep['message'] = $e->getMessage();
            $rep['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $rep;
    }


    public function card($user)
    {
        try {
            if (!$user) {
                throw new Exception('请登录');
            }

            $this->_getQrcode($user, $qr, $shareUrl);

            $dir = public_path() . 'upload/share_app/invite/' . time_format(time(), 'Ym/');
            $url = '/upload/share_app/invite/' . time_format(time(), 'Ym/') . $user['shareCode'] . '.png';

            if (!is_dir($dir)) {
                //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
                mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
            }

            $image = ImageThink::open(public_path() . '/upload/card.png');

            $image = $image->water(public_path() . $qr, [190, 450])->text($user->getData('mobile'),
                root_path() . 'data' . DIRECTORY_SEPARATOR . 'ttf' . DIRECTORY_SEPARATOR . 'simsun.ttc', 20, '#727272', [396, 208])
                ->text('F' . $user['shareCode'],
                    root_path() . 'data' . DIRECTORY_SEPARATOR . 'ttf' . DIRECTORY_SEPARATOR . 'simsun.ttc', 20, '#727272', [402, 132])
                ->text($user['nickname'],
                    root_path() . 'data' . DIRECTORY_SEPARATOR . 'ttf' . DIRECTORY_SEPARATOR . 'simsun.ttc', 20, '#727272', [400, 52]);
            $image->save($dir . $user['shareCode'] . '.png');
            $data['data']['qr_code_share'] = $this->request->domain() . $url;
            $data['data']['url'] = $url;
            $data['data']['code_image'] = $this->request->domain() . $qr;
            $data['data']['register_url'] = $shareUrl;
            $data['data']['share_desc'] = '邀请加入云副业';
            $data['data']['share_title'] = '邀请加入云副业';
            $data['data']['mobile'] = $user->getData('mobile');


            $data['code'] = 0;

        } catch (\Exception $e) {
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }


    public function goodPoster($good, $user)
    {
        try {
            if (!$user) {
                throw new Exception('请登录');
            }
            $userDynamic = UserDynamicModel::where('user_id', $user['id'])->where('shareNum',$good['id'])->where('poster_id', 0)->find();
            if (!$userDynamic) {
                $insert['poster_id'] = 0;
                $insert['shareNum'] = $good['id'];
                $insert['uid'] = $user['id'];
                $insert['poster_image'] = '';
                $insert['encryptionCode'] = '';
                $insert['code_image'] = '';
                $insert['handleNum'] = 0;
                $insert['shareCode'] = $user['shareCode'];
                $insert['user_id'] = $user['id'];
                UserDynamicModel::create($insert);
                $data['data']['tips'] = '海报生成中，请10分钟后再来下载';
                $data['data']['poster'] = '';
            } else {
                if (strlen($userDynamic['poster_image'])<30) {
                    $data['data']['tips'] = '海报还未生成完毕，请5分钟后再来下载';
                    $data['data']['poster'] = '';
                } else {
                    $data['data']['tips'] = '海报已经生成，是否下载？';
                    $data['data']['poster'] = $userDynamic;
                }
            }
            //public_path
            $data['code'] = 0;

        } catch (\Exception $e) {
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    public function autoBuild()
    {
        try {

            $userDynamic = UserDynamicModel::where('poster_image', '')->where('poster_id', 0)->order('id ASC')->find();
            if ($userDynamic) {
                $user = UserModel::where('id', $userDynamic['user_id'])->find();
                include_once app()->getRootPath() . 'extend/phpqrcode.php';
                $temp_dir = public_path() . 'upload/zip/temp/' . time_format(time(), 'Ym/') . $user['shareCode'] . '/';
                if (!is_dir($temp_dir)) {
                    //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
                    mkdir(iconv("UTF-8", "GBK", $temp_dir), 0777, true);
                }
                $this->buildPoster($user, $temp_dir, 70);
                $this->buildPoster($user, $temp_dir, 50);

                $image = new Attachment();
                $file_path = $image->generateZip($temp_dir);

                $userDynamic['poster_image'] = '/'.str_replace(public_path(), '', $file_path);
                $userDynamic->save();
            }
            //public_path
            $data['code'] = 0;
            $data['message'] = 0;

        } catch (\Exception $e) {
            $data['code'] = 2;
            $data['message'] = $e->getMessage();
            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    protected function buildPoster($user, $temp_dir, $size = 70)
    {
        $qr = '/upload/share_app/code_b/' . $user['shareCode'] . '.png';
        $dir = public_path() . 'upload/share_app/code_b/';
        if (!is_dir($dir)) {
            //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
            mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
        }

        $shareUrl = 'https://web.yunfuye.com/#/pages/login/register?inviteCode=' . $user['shareCode'];
        if (is_file(public_path() . $qr)) {
            $file_p = public_path() . $qr;
            @unlink($file_p);
        }
        $errorCorrectionLevel = 'L';//容错级别
        if ($size == 70) {
            \QRcode::png($shareUrl, public_path() . $qr, $errorCorrectionLevel, 20, 2);
        } else {
            \QRcode::png($shareUrl, public_path() . $qr, $errorCorrectionLevel, 16, 2);
        }

        if ($size == 70) {
            $image = ImageThink::open(public_path() . '/upload/poster/50X70.png');
            $image = $image->water(public_path() . $qr, [4609, 7038]);
            $image->save($temp_dir . '50X70.png', null, 50);
        } else {
            $image = ImageThink::open(public_path() . '/upload/poster/42X57.png');
            $image = $image->water(public_path() . $qr, [3919, 5708]);
            $image->save($temp_dir . '42X57.png', null, 50);
        }
    }
//    public function poster($posterPatch,$QR)
//    {
//        try {
//            if (!$user) {
//                throw new Exception('请登录');
//            }
//
//            $this->_getQrcode($user,$qr,$shareUrl);
//
//            $dir = public_path() . 'upload/share_app/invite/' . time_format(time(), 'Ym/');
//            $url = '/upload/share_app/invite/' . time_format(time(), 'Ym/') . $user['shareCode'] . '.png';
//
//            if (!is_dir($dir)) {
//                //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
//                mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
//            }
//
//            $image = ImageThink::open(public_path() . '/upload/card.png');
//
//            $image = $image->water(public_path() . $qr, [190, 450])->text($user['mobile'],
//                root_path() . 'data' . DIRECTORY_SEPARATOR . 'ttf' . DIRECTORY_SEPARATOR . 'simsun.ttc', 20, '#00000000', [400, 208])
//                ->text($user['shareCode'],
//                    root_path() . 'data' . DIRECTORY_SEPARATOR . 'ttf' . DIRECTORY_SEPARATOR . 'simsun.ttc', 20, '#00000000', [402, 132])
//                ->text($user['mobile'],
//                    root_path() . 'data' . DIRECTORY_SEPARATOR . 'ttf' . DIRECTORY_SEPARATOR . 'simsun.ttc', 20, '#00000000', [400, 52]);
//            $image->save($dir . $user['shareCode'] . '.png');
//            $data['data']['qr_code_share'] = $this->request->domain().$url;
//            $data['data']['url'] = $url;
//            $data['data']['code_image'] = $this->request->domain().$qr;
//            $data['data']['register_url'] = $shareUrl;
//            $data['data']['share_desc'] = '邀请加入云副业';
//            $data['data']['share_title'] = '邀请加入云副业';
//
//
//
//            $data['code'] = 0;
//
//        } catch (\Exception $e) {
//            $data['code'] = 2;
//            $data['message'] = $e->getMessage();
//            $data['debug'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $data;
//    }

    protected function _getQrcode($user, &$qr, &$shareUrl)
    {
        $qr = '/upload/share_app/code/' . $user['shareCode'] . '.png';
        $dir = public_path() . 'upload/share_app/code/';
        if (!is_dir($dir)) {
            //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
            mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
        }
//        $shareUrl = str_replace('v3','h5',$this->request->domain()).'/pages/login/register?inviteCode=' . $user['shareCode'];
        $shareUrl = 'https://web.yunfuye.com/#/pages/login/register?inviteCode=' . $user['shareCode'];
        if (!is_file(public_path() . $qr)) {
            $re = create_qr_code($shareUrl, $qr, public_path() . '/upload/logo.png');
        }
    }


}
